#include "ZCache.h"
#include "leveldb/db.h"

namespace ZuiLib
{

ZCache::ZCache() 
	:m_db(nullptr)
{
}

ZCache::~ZCache() {
	Close();
}

bool ZCache::Open(const std::string &file) {
	if(m_db)
		Close();

	leveldb::Options  options;
	options.create_if_missing = true;
	options.error_if_exists = false;

	leveldb::Status status = leveldb::DB::Open(options, file, &m_db);
	return status.ok();
}

void ZCache::Close() {
	delete m_db;
	m_db = nullptr;
}

bool ZCache::SetData(const std::string &key, const std::string &value) {
	if (!m_db)
		return false;

	leveldb::Status status = m_db->Put(leveldb::WriteOptions(), key,value);
	return status.ok();
}

bool ZCache::GetData(const std::string &key, std::string *value) {
	if (!m_db)
		return false;

	leveldb::Status status = m_db->Get(leveldb::ReadOptions(), key, value);
	return status.ok();
}

bool ZCache::Remove(const std::string &key) {
	if (!m_db)
		return false;
	leveldb::Status status = m_db->Delete(leveldb::WriteOptions(), key);
	return status.ok();
}

bool ZCache::Delete(const std::string &file) {
	leveldb::Options  options;
	leveldb::Status status = leveldb::DestroyDB(file, options);
	return status.ok();
}

bool ZCache::Repair(const std::string &file) {
	leveldb::Options  options;
	leveldb::Status status = leveldb::RepairDB(file, options);
	return status.ok();
}


}//namespace
